﻿namespace SPDeploy.Library.Helpers
{
    using System.Configuration;
    using Interfaces;
    using Processing.Library;

    public class ApplicationToProcessorSettingsWireUp : IProcessorSettingsWireUp
    {
        #region Fields: private

        private readonly ApplicationSettingsBase _appSettings;

        #endregion

        public ApplicationToProcessorSettingsWireUp(ApplicationSettingsBase appSettings)
        {
            _appSettings = appSettings;
        }

        #region IProcessorSettingsWireUp Members

        public void Wireup(ProcessorSettingsManager manager, ILogWriter logger)
        {
            string configName = manager.ConfigName;
            foreach (string configValueName in manager.ConfigKeys)
            {
                string appSettingKey = configName + configValueName;

                logger.Write(LogSeverity.Verbose, "SettingsWireUp", "Looking for application setting '{0}'", appSettingKey);

                if (_appSettings.Properties[appSettingKey] == null)
                {
                    logger.Write(LogSeverity.Verbose, "SettingsWireUp", "AppSetting not found, existing value is '{0}'", manager.GetConfigValue(configValueName));
                    continue;
                }

                object property = _appSettings[appSettingKey];
                if (property != null)
                {
                    logger.Write(LogSeverity.Verbose, "SettingsWireUp", "Setting value '{0}'", property);
                    manager.SetConfigValue(configValueName, property);
                }
            }
        }

        #endregion
    }
}